package com.antgroup.seckill.business.common.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.antgroup.seckill.business.common.vo.response.GoodsVo;
import com.antgroup.seckill.business.goods.model.SeckillMessage;
import com.antgroup.seckill.business.goods.model.SeckillOrder;
import com.antgroup.seckill.business.goods.service.IGoodsService;
import com.antgroup.seckill.business.goods.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author wangxy
 * @date 2024/8/3 20:01
 */
@Service
@Slf4j
public class MQConsumer {

   /* @RabbitListener(queues = "queue")
    public void consumer(Object msg) {
        log.info("接收到的消息：" + msg);
    }

    @RabbitListener(queues = "queue_topic01")
    public void consumer1(Object msg) {
        log.info("QUEUEO1接收到的消息：" + msg);
    }

    @RabbitListener(queues = "queue_topic02")
    public void consumer2(Object msg) {
        log.info("QUEUEO2接收到的消息：" + msg);
    }*/

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IOrderService iOrderService;

    //下单
    @RabbitListener(queues = "seckillQueue")
    public void consumerSeckill(String message) {

        log.info("接收到的消息为：" + message);

        SeckillMessage seckillMessage = JSON.parseObject(message, SeckillMessage.class);

        GoodsVo goodsVo = goodsService.queryGoodsByGoodsId(seckillMessage.getGoogsId());
        if(goodsVo.getSeckillCount() < 1) {
            return;
        }

        //判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("seckill:" + seckillMessage.getUser().getId() + ":" + seckillMessage.getGoogsId());
        if (Objects.nonNull(seckillOrder)) {
            return;
        }

        //下单
        iOrderService.seckillGoods(goodsVo,seckillMessage.getUser());

    }
}
